package web.kx;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import org.apache.log4j.Logger;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.http.ConnectionManager;
import org.htmlparser.http.ConnectionMonitor;
import org.htmlparser.http.HttpHeader;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.NodeVisitor;

public class WapParser {
	private static final long DELAY = 10000;
	private Parser kit = null;
	private ConnectionManager cm = null;
	private Nf nf;
	private VerifyExFilter verifyExFilter = new VerifyExFilter();
	static Logger logger = Logger.getLogger("Main");

	public WapParser() {
		kit = new Parser();
		cm = Parser.getConnectionManager();
		Hashtable<String, String> requestProperties = new Hashtable<String, String>();
		requestProperties
				.put(
						"User-Agent",
						"Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16");
		cm.setCookieProcessingEnabled(true);
		cm.setRequestProperties(requestProperties);
		try {
			kit.setEncoding("UTF-8");
		} catch (ParserException e1) {
			e1.printStackTrace();
		}
		HttpURLConnection
				.setDefaultRequestProperty(
						"User-Agent",
						"Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16");
		nf = new Nf();
		try {
			InetAddress address = InetAddress.getLocalHost();
			if (address.toString().startsWith("192.168")) {

			} else {
				System.getProperties().put("proxySet", "true");
				System.getProperties().put("proxyHost", "15.105.253.234");
				System.getProperties().put("proxyPort", "8080");
			}
		} catch (UnknownHostException e) {
			logger.error(e);
		}
		// ConnectionMonitor monitor = new ConnectionMonitor() {
		// public void preConnect(HttpURLConnection connection) {
		// logger.info(HttpHeader.getRequestHeader(connection));
		// }
		//
		// public void postConnect(HttpURLConnection connection) {
		// logger.info(HttpHeader.getResponseHeader(connection));
		// }
		// };
		CookieManager manager = new CookieManager();
		manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
		CookieHandler.setDefault(manager);
		// cm.setMonitor(monitor);
	}

	public String[] clickFilter(String url, String name) {
		return clickFilterPost(url, name, null);
	}

	public String[] click(String url) {
		return clickFilterPost(url, null, null);
	}

	static int clickcount = 0;

	public String[] clickWithCheck(String url, String keyword) {
		return clickFilterKeywordPost(url, null, keyword, null);
	}

	public String[] clickFilterPost(String url, final String linkFilter,
			String post) {
		return clickFilterKeywordPost(url, linkFilter, null, post);
	}

	static long lastTimer = 0;
	static {
		lastTimer = System.currentTimeMillis();
	}

	public String[] clickFilterKeywordPost(String url, final String linkFilter,
			String keyword, String post) {
		synchronized (this) {
			long curr = 0;
			while ((curr = System.currentTimeMillis()) - lastTimer < 3000) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					logger.error(e);
				}
			}
			lastTimer = curr;
		}
		logger.info("CLICK=" + ++clickcount + "  FINDING " + linkFilter
				+ " CHECKING " + keyword + "repeat times=" + ++repeatCount);
		logger.info(url);
		URLConnection openConnection;
		String[] nls = null;
		NodeList nodeList = null;
		NodeList verifyEx = null;
		NodeList all = null;
		// Parser tParser=null;
		try {
			openConnection = new URL(url).openConnection();
			// openConnection = cm.openConnection(url);
			if (post != null) {
				logger.info("post="+post);
				openConnection.setDoOutput(true);
				OutputStreamWriter out = new OutputStreamWriter(openConnection
						.getOutputStream(), "UTF-8");
				out.write(post);
				out.flush();
				out.close();
			}
			// tParser = new Parser(openConnection);
			// tParser.setEncoding("utf-8");
			kit.setConnection(openConnection);
			all = kit.parse(null);
			((HttpURLConnection) openConnection).disconnect();
			if (linkFilter == null) {
				all.extractAllNodesThatMatch(nf, true);
			} else {
				nodeList = all.extractAllNodesThatMatch(new Nf(linkFilter),
						true);
			}
			// verifyEx = all.extractAllNodesThatMatch(verifyExFilter, true);
		} catch (Exception e) {
			logger.error(e);
		}
		if (null != nodeList && nodeList.size() >= 1) {
			ArrayList<String> list = new ArrayList<String>();
			logger
					.info("GETTING URLS===============================================");
			for (int i = 0; i < nodeList.size(); i++) {
				Node pare = nodeList.elementAt(i).getParent();
				if (pare != null) {
					String x = getUrlAndCheck(pare.getText());
					if (x != null) {
						logger.info("url[" + i + "]:" + x);
						list.add(x);
					}
				}
			}
			nls = list.toArray(new String[list.size()]);
			logger.info("end===============================================");
		}
		boolean yzm = false;
		try {
			yzm = (all.toHtml(true) != null && all.toHtml(true).indexOf("验证码") == -1);
		} catch (NullPointerException e) {
			return clickFilterKeywordPost(url, linkFilter, keyword, post);
		}
		if (all.toHtml(true).indexOf("自动为我登录") != -1) {
			clickFilterPost(
					"http://wap.kaixin001.com/home/", "组件", "email=" + Config.getProperty("用户")
							+ "&" + "password=" + Config
							.getProperty("密码") + "&"
							+ "remember=1&from=&refuid=0&refcode=&login=提交");
			Notifer.error();
			return null;
		}
		if (!yzm) {
			Notifer.error();
			try {
				Thread.sleep(120 * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (repeatCount <= MAX_REPEAT_COUNT) {
				VERIFY_CURRTIME = System.currentTimeMillis();
				nls = clickFilterKeywordPost(url, linkFilter, keyword, post);
			} else {
				Notifer.error();
				try {
					Thread.sleep(50 * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.exit(1);
			}
		} else if (keyword != null && all.toHtml(true).indexOf(keyword) == -1) {
			Notifer.warning();
			if (repeatCount <= MAX_REPEAT_COUNT) {
				if (VERIFY_CURRTIME == -1) {
					VERIFY_CURRTIME = System.currentTimeMillis();
				}
				nls = clickFilterKeywordPost(url, linkFilter, keyword, post);
			} else {
				Notifer.error();
				try {
					Thread.sleep(50 * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.exit(1);
			}

		}
		VERIFY_CURRTIME = System.currentTimeMillis();
		repeatCount = 0;
		return nls;
	}

	int repeatCount = 0;
	final static int MAX_REPEAT_COUNT = 30;
	final static long VERIFY_MAX_WAIT = 10 * 1000;
	long VERIFY_CURRTIME = -1;

	public static String getUrlAndCheck(String s) {
		String x = null;
		if (!(null == s || "".equals(s))) {
			int indexOf = s.indexOf("href=\"");
			if (-1 != indexOf) {
				int indexOfx = s.indexOf("\"", indexOf + 6);
				x = s.substring(indexOf + 6, indexOfx);
				if (x.startsWith("/")) {
					x = "http://wap.kaixin001.com" + x;
				}
				x = x.replaceAll("&nbsp;", "").replaceAll("&amp;", "&");
			}
		}
		return x;
	}
}

class Nf implements NodeFilter {
	private static final long serialVersionUID = 1L;
	private String ss[] = null;
	private static Logger logger = Logger.getLogger("Main");

	public Nf() {

	}

	public Nf(String s) {
		ss = new String[] { s };
	}

	public Nf(String[] ss) {
		this.ss = ss;
	}

	public boolean accept(Node arg0) {
		String htmlEle = arg0.getText();
		String text = htmlEle;
		String replaceAll = text.replaceAll("\\s+", " ")
				.replaceAll("^\\s+", "").replaceAll("\\s+$", "").replaceAll(
						"&nbsp;", "").replaceAll("&amp;", "&").replaceAll(
						"^b$", "").replaceAll("^p$", "").replaceAll("^div.*$",
						"").replaceAll("^font.*$", "").replaceAll("^\\|$", "")
				.replaceAll("^body.*$", "").replaceAll("^style.*$", "")
				.replaceAll("^html.*$", "").replaceAll("^!DOCTYPE.*$", "")
				.replaceAll("^\\?xml.*$", "").replaceAll("开心网", "");
		if (replaceAll.length() != 0 && !text.startsWith("/")
				&& !text.endsWith("/")) {
			logger.debug(replaceAll);
		}
		// if(arg0 instanceof org.htmlparser.tags.LinkTag){
		// logger.info("linkTag"+arg0.getText());
		// }else if (arg0 instanceof org.htmlparser.nodes.TextNode){
		// logger.debug("TextNode"+arg0.getText());
		// }
		// if (text.indexOf("验证码") != -1 || text.indexOf("不能再做菜了") != -1
		// || text.indexOf("操作失败") != -1) {
		// logger.error("XXXXXXXverifycation" + text);
		// Notifer.callUser();
		// }
		if (ss != null) {
			for (int i = 0; i < ss.length; i++) {
				String array_element = ss[i];
				if (htmlEle.indexOf(array_element) != -1) {
					logger.debug("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
					return true;
				}
			}
			return false;
		}
		return true;
	}
}

class VerifyExFilter implements NodeFilter {

	private static final long serialVersionUID = 1382406664333763473L;

	public boolean accept(Node arg0) {
		String text = arg0.getText();
		if (text.indexOf("验证码") != -1) {
			WapParser.logger.error("\n验证码");
			return true;
		}
		if (text.indexOf("不能再做菜了") != -1) {
			Notifer.info();
			WapParser.logger.error("\n不能再做菜了");
		}
		if (text.indexOf("操作失败") != -1) {
			Notifer.info();
			WapParser.logger.error("\n操作失败");
		}
		return false;
	}

	class NodeV extends NodeVisitor {

	}
}
